package org.devocean.groupbuying.service.security;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class BackendAuthProcessingFilter extends UsernamePasswordAuthenticationFilter {

	 @SuppressWarnings("deprecation")
	@Override
	    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
	        SavedRequestAwareAuthenticationSuccessHandler srh = new SavedRequestAwareAuthenticationSuccessHandler();
	        this.setAuthenticationSuccessHandler(srh);
	        srh.setRedirectStrategy(new RedirectStrategy() {

				public void sendRedirect(HttpServletRequest arg0,
						HttpServletResponse arg1, String arg2)
						throws IOException {
					// TODO Auto-generated method stub
					
				}
	        });
	        super.successfulAuthentication(request, response, authResult);
	        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
	        Writer out = responseWrapper.getWriter();
	        System.out.println("login success");
	        out.write("{success:true}");
	        out.close();
	    }

	    @Override
	    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
	        super.unsuccessfulAuthentication(request, response, failed);
	        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
	        Writer out = responseWrapper.getWriter();
	        out.write("{success:false}");
	        out.close();
	    }
	
}
